package fds.framework.buiz;

import java.util.ArrayList;
import java.util.List;

import fds.framework.data.DATA_THREAD_RES;
import fds.framework.type.TYPE_PROC_STATE;

public class ScheduleJenga extends Thread
{
	private static List<ThreadJenga> workLst = new ArrayList<ThreadJenga>();
	private static List<ThreadJenga> workEnd = new ArrayList<ThreadJenga>();
	private static long              workNum = 0000000000000000000L;
	private static int               mt = 0;
	private static int               ct = 0;
	
	public synchronized static void setMaxThread(int MaxThread)
	{
		ScheduleJenga.mt = MaxThread;
		while(ScheduleJenga.ct < ScheduleJenga.mt) new ScheduleJenga(ScheduleJenga.ct++);
	}
	
	public synchronized static int getWorkListCnt()
	{
		return workLst.size();
	}
	
	public synchronized static DATA_THREAD_RES getWorkEnd(long WorkNo)
	{
		ThreadJenga nowTj = null;
		for(ThreadJenga tj : workEnd)
		{
			if(tj.getWorkNo() == WorkNo)
			{
				nowTj = tj;
				break;
			}
		}
		if(nowTj != null)
		{
			workEnd.remove(nowTj);
			return new DATA_THREAD_RES(nowTj.getProcState(), nowTj.getResultLs());
		}
		return null;
	}
	
	private int myThreadNumber = 0;
	
	private ScheduleJenga(int ThreadNumber)
	{
		this.myThreadNumber = ThreadNumber;
		this.start();
	}
	
	public synchronized static void addWork(ThreadJenga threadJanga)
	{
		System.out.println("ADDWORKS " + threadJanga.getClass().getName());
		if(workNum == 1000000000000000000L) workNum = 0000000000000000000L;
		threadJanga.setWorkNo(++workNum);
		workLst.add(threadJanga);
	}
	
	public void run()
	{
		System.out.println("Thread[" + this.myThreadNumber + "] Run");
		while((this.myThreadNumber < ScheduleJenga.mt) || (this.myThreadNumber == 0 && ScheduleJenga.mt < 2 && workLst.size() > 0))
		{
			System.out.println("Thread[" + this.myThreadNumber + "] Check");
			ThreadJenga nowWork = null;
			synchronized(this)
			{
				int nowSize = workLst.size(); 
				if(nowSize > 0)
				{
					for(int i=0;i<nowSize;i++)
					{
						ThreadJenga tmpWork = workLst.get(i);
						if(tmpWork.getProcState() == TYPE_PROC_STATE.RUNABLE)
						{
							nowWork = tmpWork;
							break;
						}
					}
				}
			}
			
			if(nowWork != null)
			{
				//System.out.println("Thread [" + this.myThreadNumber + "] Work " + nowWork.getClass().getName());
				nowWork.startThread();
				synchronized (this) 
				{
					workLst.remove(nowWork);
					workEnd.add(nowWork);
				}
			}
			try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); }
		}
		synchronized(this)
		{
			ScheduleJenga.ct--;
		}
		System.out.println("Thread [" + this.myThreadNumber + "] End");
	}
}
